package com.zhouzhou.fastjava.vfs;

import com.zhouzhou.fastjava.vfs.exception.VFSException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public abstract class AbstractVFS implements VFS {

    @Override
    public final void store(InputStream is, String dir, String filename) throws VFSException {

        if (StringUtils.isBlank(dir)) {
            dir = "/";
        }
        if (!dir.startsWith("/")) {
            dir = "/" + dir;
        }
        if (!dir.endsWith("/")) {
            dir = dir + "/";
        }
        this.mkdirs(dir);
        this.storeInternal(is, dir, filename);
        this.clean(dir, filename);
    }

    @Override
    public final void retrieve(String uri, OutputStream os) throws VFSException, FileNotFoundException {
        try {
            IOUtils.copy(retrieve(uri), os);
        } catch (IOException e) {
            throw new VFSException("retrieve file error", e);
        }
    }

    protected abstract void storeInternal(InputStream is, String dir, String filename);

    protected abstract void mkdirs(String dir);

    protected void clean(String dir, String filename) {
    }

}